﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VerificationCode
{
    class ValidateCode
    {
        //创建验证码
        public static string CreateVCode(int length)
        {
            //随机数的数组，长度由用户定义
            int[] randNumbers = new int[length];
            //验证码的数组，长度由用户定义
            int[] validateNums = new int[length];
            //生成验证码后要返回的值
            string validateNumberStr = "";

            //生成起始序列值，unchecked表示不再检测是否溢出，截取部分内容，作为随机数种子
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);

            //根据用户输入的位数去生成随机数
            int beginSeek = seekRand.Next(0, Math.Abs(seekSeek) - length * 10000);

            //用于存放随机数
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 125009;
                seeks[i] = beginSeek;
            }

            //生成随机数字
            for (int i = 0; i < length; i++)
            {
                Random rd = new Random(seeks[i]);
                int pownum = 2 * (int)Math.Pow(8, length);
                randNumbers[i] = rd.Next(pownum, Int32.MaxValue);
            }

            //抽取随机数
            for (int i = 0; i < length; i++)
            {
                string numStr = randNumbers[i].ToString();
                int numLength = numStr.Length;
                Random rd = new Random();
                //从字符串长度中，随机获取一个数，表示截取坐标
                int numPosition = rd.Next(0, numLength - 1);
                //截取字符串的某一位
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }

            //从验证码数组中获取值
            foreach (var item in validateNums)
            {
                validateNumberStr += item.ToString();
            }

            return validateNumberStr;
        }
    }
}
